import { ref, reactive, onMounted, type Ref } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { DeviceItem } from "./type/deviceTypes";
import type { FormItemProps } from "./type/deviceTypes";
import { h } from "vue";
import deviceForm from "../componentsForm/deviceForm.vue";
import { setOriginalDeviceId } from "./rule/deviceRules";

export function useDeviceTable(
  tableRef: Ref,
  lesseeId: number,
  tenantName: string,
  dealerId: number,
  dealerName: string
) {
  const form = reactive({
    name: "",
    code: "",
    type: "",
    deviceGroup: "",
    SearchTerm: "",
    OrderBy: "",
    zoneId: "",
    groupId: ""
  });
  const formRef = ref();
  const dataList = ref<DeviceItem[]>([]);
  const loading = ref(true);
  const selectedNum = ref(0);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 列表列定义
  const columns = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "名称",
      prop: "Name",
      minWidth: 120
    },
    {
      label: "编码",
      prop: "Code",
      minWidth: 100
    },
    {
      label: "类型",
      prop: "TypeLabel",
      minWidth: 100,
      slot: "type"
    },
    {
      label: "分组",
      prop: "GroupName",
      minWidth: 120
    },
    {
      label: "备注",
      prop: "Comment",
      minWidth: 150
    },
    {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    }
  ];

  // 设备类型选项
  const deviceTypeOptions = [
    { label: "摄像头", value: 1 },
    { label: "广播机", value: 2 },
    { label: "对讲设备", value: 3 }
  ];

  // 设备组选项 - 改为响应式变量
  const deviceGroupOptions = ref<any[]>([]);

  //获取设备分组列表
  function fetchDeviceGroups() {
    const params = {
      PageIndex: 1,
      PageSize: 100, // 获取所有设备分组
      tenantId: lesseeId
    };

    http
      .get(changeHttpLink("/api/DeviceGroup"), {
        params
      })
      .then((res: any) => {
        if (res.Success) {
          // 将获取到的设备分组转换为下拉框选项格式
          deviceGroupOptions.value = res.Data.Items.map((item: any) => ({
            label: item.Name,
            value: item.Id
          }));
          // 添加默认选项
          deviceGroupOptions.value.unshift({
            label: "默认分组",
            value: 0
          });
          console.log("设备分组列表数据:", deviceGroupOptions.value);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        console.log(err);

        message("获取设备分组列表失败", { type: "error" });
      });
  }
  // 获取、搜索设备列表
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize,
      OrderBy: form.OrderBy,
      IsDesc: false,
      SearchTerm: form.SearchTerm,
      zoneId: form.zoneId,
      groupId: form.groupId,
      tenantId: lesseeId
    };
    console.log("请求参数:", params);

    http
      .get(changeHttpLink("/api/Device"), {
        params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          //console.log("设备列表数据:", res.Data.Items);

          // 为每个设备项添加TenantName和DealerName字段，并处理Type显示
          dataList.value = (res.Data.Items || []).map(item => {
            // 根据Type值获取对应的设备类型名称
            const typeOption = deviceTypeOptions.find(
              option => option.value === item.Type
            );
            // 处理GroupName为空或为null的情况
            const groupName = item.GroupName || "无分组";
            return {
              ...item,
              TenantName: tenantName,
              DealerName: dealerName,
              TypeLabel: typeOption ? typeOption.label : "未知类型",
              GroupName: groupName
            };
          });
          pagination.total = res.Data.TotalCount || 0;
          console.log(dataList.value);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        console.log(err);

        loading.value = false;
        message("接口暂时不可用，使用模拟数据", { type: "warning" });
      });
  }

  // 新增、修改设备
  function openDialog(title: string, row: any = null) {
    const id = row?.Id ?? 0;
    // 设置原始设备ID
    setOriginalDeviceId(id, lesseeId);
    addDialog({
      title: `${title}设备`,
      props: {
        formInline: {
          id: row?.Id ?? 0,
          dealerId: dealerId,
          tenantId: lesseeId,
          groupId: row?.GroupId ?? 0,
          zoneId: row?.ZoneId ?? 0,
          name: row?.Name ?? "",
          code: row?.Code ?? "",
          type: row?.Type ?? 0,
          params: row?.Params ?? "",
          comment: row?.Comment ?? "",
          isOnline: row?.IsOnline ?? false
        },
        title: title,
        originalDeviceId: id,
        tenantId: lesseeId
      },
      width: "640px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(deviceForm, {
          ref: formRef,
          formInline: null,
          title: title,
          deviceGroupOptions: deviceGroupOptions.value,
          originalDeviceId: id,
          tenantId: lesseeId
        }),

      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`您${title}了设备ID为【${curData.id}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              ...curData
            };
            console.log(formData);
            if (title === "创建") {
              http
                .post(changeHttpLink("/api/Device"), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            } else {
              http
                .request("put", changeHttpLink(`/api/Device/${id}`), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            }
          }
        });
      }
    });
  }

  // 删除设备
  function handleDelete(row: DeviceItem) {
    ElMessageBox.confirm(
      `是否确认删除设备ID为${row.Id}的这条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .request("delete", changeHttpLink(`/api/Device/${row.Id}`), {
            data: row.Id
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`您删除了设备ID为${row.Id}的这条数据`, {
                type: "success"
              });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listIds = curSelected.map(item => item.Id);

    ElMessageBox.confirm(
      `是否确认删除选中的${listIds.length}条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/Device/batch-delete"), {
            data: { ids: listIds }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已删除选中的${listIds.length}条数据`, {
                type: "success"
              });
              tableRef.value.getTableRef().clearSelection();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 分页大小变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    onSearch();
  }

  // 处理当前页变化
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 多选框变化
  function handleSelectionChange(val: DeviceItem[]) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  // 多选框反选
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  // 重置表单
  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  // 设备检测
  function deviceDetection() {
    return window.innerWidth <= 1024;
  }

  onMounted(() => {
    // 初始化加载数据
    onSearch();
    fetchDeviceGroups();
  });

  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    deviceTypeOptions,
    deviceGroupOptions,
    fetchDeviceGroups
  };
}
